package cn.kgc.vue.service.impl;

import cn.kgc.vue.commons.QueryCondition;
import cn.kgc.vue.commons.ResponseResult;
import cn.kgc.vue.entity.Permission;
import cn.kgc.vue.entity.RolePers;
import cn.kgc.vue.entity.UserRole;
import cn.kgc.vue.mapper.PermissionMapper;
import cn.kgc.vue.mapper.RolePersMapper;
import cn.kgc.vue.mapper.UserRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.vue.entity.Role;
import cn.kgc.vue.service.RoleService;
import cn.kgc.vue.mapper.RoleMapper;
import jdk.jfr.TransitionTo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 11839
* @description 针对表【sys_role】的数据库操作Service实现
* @createDate 2024-06-28 15:23:44
*/
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role>
    implements RoleService{

    private final UserRoleMapper userRoleMapper;
    private final RolePersMapper rolePersMapper;
    private final PermissionMapper permissionMapper;

    public RoleServiceImpl(UserRoleMapper userRoleMapper, RolePersMapper rolePersMapper, PermissionMapper permissionMapper) {
        this.userRoleMapper = userRoleMapper;
        this.rolePersMapper = rolePersMapper;
        this.permissionMapper = permissionMapper;
    }

    @Override
    public ResponseResult rolePage(QueryCondition<Role> params) {
        Page<Role> rolePage = new Page<>(params.getPage(), params.getLimit());
        Role searchParams = params.getSearchParams();
        String roleEn = searchParams.getRoleEn();
        String roleCh = searchParams.getRoleCh();

        LambdaQueryWrapper<Role> lambda = new QueryWrapper<Role>().lambda();
        lambda.like(StringUtils.isNotEmpty(roleCh), Role::getRoleCh, roleCh)
                .like(StringUtils.isNotEmpty(roleEn), Role::getRoleEn, roleEn);

        baseMapper.selectPage(rolePage,lambda);


        return ResponseResult.success().data("total", rolePage.getTotal()).data("rows", rolePage.getRecords()).data("tableData", rolePage.getRecords());
    }

    @Transactional
    @Override
    public ResponseResult deleteRoal(Integer id) {
        //对于要删除的角色，得先判断是否还有正在使用该角色的用户，如果有 得先提示移除该用户 然后删除该角色
        //1、先去查 是否还有使用该角色的用户
        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getRoleId, id);

        List<UserRole> userRoles = userRoleMapper.selectList(lambda);
        if (!userRoles.isEmpty()){
            return ResponseResult.fail().message("请移除该角色的用户再进行删除操作");
        }
        //如果没有用该角色的用户 即可删除
        baseMapper.deleteById(id);

        //那么同时 角色和权限关联表也都可以删除
        LambdaQueryWrapper<RolePers> lambda1 = new QueryWrapper<RolePers>().lambda();
        lambda1.eq(RolePers::getRoleId, id);
        rolePersMapper.delete(lambda1);


        return ResponseResult.success().message("删除成功");
    }

    @Override
    public ResponseResult getRoleById(Integer rid) {
        // 先通过 rid 查出 perid 然后通过 perid 查出 ismenu 为 2 的
        LambdaQueryWrapper<RolePers> lambda = new QueryWrapper<RolePers>().lambda();
        lambda.eq(RolePers::getRoleId, rid);
        List<Integer> collect = rolePersMapper.selectList(lambda).stream()
                .map(RolePers::getPerId)
                .collect(Collectors.toList());

        List<Integer> collect1 = new ArrayList<>();
        if (!collect.isEmpty()) {
            LambdaQueryWrapper<Permission> lambda1 = new QueryWrapper<Permission>().lambda();
            lambda1.eq(Permission::getIsMenu, 2)
                    .in(Permission::getId, collect);

            collect1 = permissionMapper.selectList(lambda1).stream()
                    .map(Permission::getId)
                    .collect(Collectors.toList());
        }

        return ResponseResult.success().data("defaultKeys", collect1);
    }


    @Transactional
    @Override
    public ResponseResult editRolePermissions(HashMap<String, Object> params) {
        //传入了两个值 一个是 当前行id 一个是集合 即将要改的
        //先拿出来
        Integer rid = (Integer) params.get("rid");
        List<Integer> newKeys = (List<Integer>) params.get("newKeys");


        LambdaQueryWrapper<RolePers> eq = new QueryWrapper<RolePers>().lambda().eq(RolePers::getRoleId, rid);


        rolePersMapper.delete(eq);

        newKeys.forEach(pid->{
            RolePers rolePers = new RolePers();
            rolePers.setRoleId(rid);
            rolePers.setPerId(pid);
            rolePersMapper.insert(rolePers);
        });


        return ResponseResult.success().message("权限分配完成");
    }
}




